<template>
<div 
    class="select-website-cp"
    @click.stop
    v-show="dataList.length>0">
    <div class="container">
        <div 
            :class="{
                'item':true,
                'active-item':currentIndex==index,
            }" 
            v-for="(item,index) in dataList" 
            :key="index"
            @click.stop="onClickItem(item,'left')"
            @contextmenu.prevent.stop="onClickItem(item,'right')"
            :data-id="item.id">
            <div class="left">
                <el-image
                    class="border-radius_1"
                    :src="item.icon"
                    fit="cover">
                    <div slot="error">
                    </div>
                </el-image>
                <div class="container">
                    <div class="name" v-html="filterName(item.name)"></div>
                    <div class="link">
                        {{item.link}}
                    </div>
                </div>
                <div class="add-bt" @click.stop="onAdd(item)">
                    +
                </div>
            </div>
            <div class="right" v-if="item.tags.length>0">
                <TagsCp 
                    :tags="item.tags">
                </TagsCp>
            </div>
        </div>
    </div>
    <AddWebsiteDialog
        ref="AddWebsiteDialog">
    </AddWebsiteDialog>
    <span class="help">
        '↑ ↓' 键选择
    </span>
</div>
</template>

<script>
/*
 选择网站组件
 */
import {formatStr} from '@/common/Tools';
import {debounceFn} from '@/common/DebounceAndThrottle';
import AddWebsiteDialog from "@/components/AddWebsite";
import TagsCp from "@/components/public/Tags";
export default {
    name: 'SelectWebsite',
    components:{
        AddWebsiteDialog,
        TagsCp,
    },
    props:{
        keyWord:{  //需要搜索的值
            type:String,
            default:'',
        },
    },
    data(){
        this.oldDataList = {};  //记录所有的搜索记录，
        return {
            dataList:[],  //搜索到的网站数据
            currentIndex:-1,  //已选中的网站索引(默认没选中)
        };
    },
    watch:{
        currentIndex(newValue){ //当索引改变时触发改变事件，暴露当前选择的网站
            this.$emit('onChange',{
                currentIndex:newValue,
                currentData:this.dataList[newValue],
            });
        },
        keyWord:{  //监听关键字，发生变化时请求符合的网站数据
            handler(newValue){
                this.getData(newValue);
            },
            immediate:true,
        },
    },
    created(){
        this.initEvent(); //添加键盘监听
    },
    methods:{
        initCurrentIndex(currentIndex=-1){  //初始化数据（外部调用）
            this.currentIndex = currentIndex;
        },
        initDataList(dataList=[]){  //初始化数据（外部调用）
            this.dataList = dataList;
        },
        onClickItem(item,option='left'){
            if(option == 'right'){  //表示鼠标右击，跳转到该网站的搜索页面中
                let search = item.search;
                let url = search.replace("{searchData}",encodeURI(this.keyWord));
                window.open(url);
            }else{
                window.open(item.link);
            }
        },
        getData:debounceFn(function(){  //根据网站名与搜索值像的网站
            this.currentIndex = -1;
            let name = formatStr(this.keyWord);
            if (!name){
                this.dataList = [];
                return;
            }
            if(this.oldDataList[name]){ //如果是搜索过的直接返回结果
                this.dataList = this.oldDataList[name];
                return;
            }
            this.$Api.searchWebsites({
                keyWord:name,
                number:7,
            }).then((data)=>{
                this.dataList = data;
                this.oldDataList[name] = data;
            });
        },150),
        initEvent(){  //初始化上下键盘按钮事件
            window.addEventListener('keydown',(event)=>{
                const e = event || window.event || arguments.callee.caller.arguments[0];
                if(!e) return false;
                if(this.dataList.length==0) return false;
                //网站选择不能加ctrl键
                if(e.shiftKey || e.ctrlKey || e.altKey) return false;  //必须只是字母键键
                if(!this.isActive()) return false;
                switch(e.keyCode){
                    case 38: //上
                        this.upKeyDown();
                        break;
                    case 40: //下
                        this.downKeyDown();
                        break;
                }
                return false;
            });
        },
        upKeyDown(){ //键盘上键按下执行
            let length = this.dataList.length;
            if (length == 0) return;
            let newIndex = this.currentIndex-1;
            if (newIndex<-1){ //选择时留个空位
                this.currentIndex = length-1;
            }else{
                this.currentIndex = newIndex;
            }
        },
        downKeyDown(){ //键盘下键按下执行
            let length = this.dataList.length;
            if (length==0) return;
            let newIndex = this.currentIndex+1;
            if (newIndex>length){ //选择时留个空位
                this.currentIndex = 0;
            }else{
                this.currentIndex = newIndex;
            }
        },
        filterName(name){  //高亮关键字
            if (!name) return '';
            let keyWord = formatStr(this.keyWord);
            return name.replace(new RegExp(keyWord, 'gi' ),'<span>'+keyWord+'</span>');
        },
        onAdd(website){ //添加网站按钮点击事件
            this.$refs.AddWebsiteDialog.setInitData(website);
        },
        isActive(){  //是否是当前活动的组件
            const el = this.$el;
            if(!el) return false;
            return !!(el.clientWidth || el.clientHeight);
        },
    },
}
</script>
<style lang="scss" scoped>
@media only screen and (min-width: 1920px){
    .select-website-cp{
        >.container{
            >.item{
                padding: 0.5rem 1.3rem;
                >.left{
                    /deep/.el-image{
                        width: 3.1rem;
                        height: 3.1rem;
                        /deep/img{
                            width: 3.1rem;
                            height: 3.1rem;
                            min-width: 3.1rem;
                        }
                    }
                    .add-bt{
                        padding: 0.5rem;
                        font-size: 3rem;
                    }
                    >.container{
                        margin: 0 1.5rem;
                        grid-gap: 0.1rem;
                        font-size: 1.9rem;
                        >.link{
                            font-size: 1.5rem;
                        }
                    }
                }
                >.right{
                    margin-left: 1rem;
                }
            }
        }
    }
}
@media only screen and (max-width: 1920px){
    .select-website-cp{
        >.container{
            >.item{
                padding: 3px 10px;
                >.left{
                    /deep/.el-image{
                        width: 25px;
                        height: 25px;
                        /deep/img{
                            width: 25px;
                            height: 25px;
                            min-width: 25px;
                        }
                    }
                    .add-bt{
                        padding: 3px 5px;
                        font-size: 25px;
                    }
                    >.container{
                        margin: 0 10px;
                        grid-gap: 1px;
                        font-size: 16px;
                        >.link{
                            font-size: 10px;
                        }
                    }
                }
                >.right{
                    margin-left: 10px;
                }
            }
        }
    }
}
.select-website-cp{
    width: 100%;
    height: fit-content;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    background-color: white;
    overflow: hidden;
    position: relative;
    box-shadow: 0 1px 5px 0 rgba(0, 0, 0, 0.211),0 1px 5px 0 rgba(0, 0, 0, 0.272);
    border-radius: 7px;
    border: 1px solid #eff1f4;
    >.container{
        width: 100%;
        box-sizing: border-box;
        height: fit-content;
        display: grid;
        grid-gap: 1px;
        background-color: rgb(236, 236, 236);
        >.item{
            display: flex;
            justify-content: space-between;
            background-color: white;
            align-items: center;
            transition: all 0.2s;
            box-sizing: border-box;
            cursor: pointer;
            &:hover{
                background-color: rgba(46, 50, 56, 0.013);
            }
            >.left{
                display: flex;
                align-items: center;
                .add-bt{
                    transition: all 0.2s;
                    line-height: 1;
                    &:hover{
                        color: red;
                    }
                }
                >.container{
                    display: grid;
                    grid-template-columns: 1fr;
                    text-align: left;
                    line-height: 1.2;
                    >.name{
                        display: inline-block;
                        white-space: nowrap;
                        width: 100%;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        /deep/span{
                            color: red;
                        }
                    }
                    >.link{
                        opacity: 0.7;
                        overflow: hidden;
                        display: inline-block;
                        white-space: nowrap;
                        width: 100%;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }
                }
            }
            >.right{
                display: flex;
                align-items: center;
            }
        }
        >.active-item{
            background-color: rgba(46, 50, 56, 0.013);
        }
    }
    >.help{
        position: absolute;
        bottom: 1rem;
        right: 1rem;
        opacity: 0.5;
        font-size: 1.5rem;
        pointer-events: none;
    }
}
</style>
